let socketOpen = false
let socketMsgQueue = []
import {
	wsUrl
} from '@/config/config.js'
import {
	Stomp
} from './stomp.js'

export class WebSocket {
	constructor(url = wsUrl) {
		this.wsUrl = url;
		this.client = null;
		this.socketOpen = false;
		this.socketMsgQueue = [];
		this.reconnectInterval = 5000;
		this.reconnectId = null;
		this.closeCallback = null;
	}

	init() {
		if (this.client) {
			return Promise.resolve(this.client);
		}

		return new Promise((resolve, reject) => {
			const ws = {
				send: this.sendMessage.bind(this),
				onopen: null,
				onmessage: null,
				close: this.closeSocket.bind(this),
			};

			uni.connectSocket({
				url: this.wsUrl
			});

			uni.onSocketOpen((res) => {
				console.log('WebSocket连接已打开！', res);
				this.socketOpen = true;
				this.socketMsgQueue.forEach(msg => ws.send(msg));
				this.socketMsgQueue = [];

				ws.onopen && ws.onopen();
			});

			uni.onSocketMessage((res) => {
				console.log("onSocketMessage", res);
				ws.onmessage && ws.onmessage(res);
			});

			uni.onSocketError((res) => {
				console.error('WebSocket 错误！', res);
			});

			uni.onSocketClose((res) => {
				this.client?.disconnect();
				this.client = null;
				this.socketOpen = false;
				console.log('WebSocket 已关闭！', res);
				if (typeof this.closeCallback === 'function') {
					this.closeCallback(res);
				}
			});

			// 设置 STOMP 心跳处理器
			Stomp.setInterval = function(interval, f) {
				return setInterval(f, interval);
			};
			Stomp.clearInterval = function(id) {
				clearInterval(id);
			};

			const client = (this.client = Stomp.over(ws));
			client.connect({},
				() => {
					console.log('STOMP 连接成功');
					resolve(client);
				},
				() => {
					this.reconnectId = setTimeout(() => {
						this.reconnect();
					}, this.reconnectInterval);
				}
			);
		});
	}

	reconnect() {
		console.warn('尝试重连...');
		this.init(); // 重新连接
	}

	disconnect() {
		uni.closeSocket();
	}

	sendMessage(message) {
		if (this.socketOpen) {
			uni.sendSocketMessage({
				data: message
			});
		} else {
			this.socketMsgQueue.push(message);
		}
	}

	closeSocket() {
		console.log('关闭 WebSocket');
		this.client?.disconnect();
		this.client = null;
		uni.closeSocket();
	}

	setCloseCallback(callback) {
		this.closeCallback = callback;
	}
}